<?php
session_start(); 
  include("../../sql/connexionmysql.php");
  include("../../controlleur/utilities.php");
  $_SESSION['admin'] = 1;
  if ($_SESSION['admin'] < 1)
		header("location:/../../index.php");
  
  $idMatch = $_POST['idTournamentMatch'];
  $match = mysql_fetch_array(mysql_query(
      'SELECT * FROM tournamentMatch NATURAL JOIN tournamentDraw WHERE idTournamentMatch = '. $idMatch));
  
  $updateMatchSql = 'UPDATE tournamentMatch SET updateDate = NOW(), ';
  
  for ($i = 1; $i <= 4; $i++) {
    $updateMatchSql .= 'idPlayer' .$i . ' = '. $_POST['player' . $i] . ', ';
  }
  
  
  /* Date and hour and field */
  $isDateHourOk = checkDateHour($_POST['hour'], $_POST['date'], $_POST['field'],
      $match['idTournament'], $idMatch);
  if ($isDateHourOk) {
    $updateMatchSql .= 'idTournamentField = '. $_POST['field'] . ', ';
    $updateMatchSql .= 'date = "'. $_POST['date'] . '", ';
    $updateMatchSql .= 'hour = '. $_POST['hour'] . ', ';
    $updateMatchSql .= 'minute = '. $_POST['minute'] . ', ';
  }
  
  
  /* Handle Scores */
  mysql_query('DELETE FROM tournamentGameScore WHERE idTournamentMatch = '. $idMatch);
  $scoreToAdd = array();
  $index = 0;
  $setCountPlayer1 = 0;
  $setCountPlayer2 = 0;
  for ($set = 1; $set <= $maxNumSet; $set++) {
    for ($p = 1; $p <= 2; $p++) {
      $otherPlayer = ($p == 1 ? 2 : 1);
      if ($_POST['player' . $p . 'set' . $set] != 0 || $_POST['player' . $otherPlayer . 'set' . $set] != 0) {
        $scoreToAdd[$index] = array();
        $scoreToAdd[$index]['idTournamentMatch'] = $idMatch;
        $scoreToAdd[$index]['setIndex'] = $set;
        $scoreToAdd[$index]['idPlayer01'] = $_POST['player' . ($p)];
        $scoreToAdd[$index]['idPlayer02'] = $_POST['player' . ($p + 2)];
        $scoreToAdd[$index]['score'] = $_POST['player' . $p . 'set' . $set];
        $index++;
        $currentPlayerWin = ($_POST['player' . $p . 'set' . $set]) > $_POST['player' . $otherPlayer . 'set' . $set];
        $setCountPlayer1 += $currentPlayerWin && $p == 1 ? 1 : 0;
        $setCountPlayer2 += $currentPlayerWin && $p == 2 ? 1 : 0;
      }
    }
  }
  
  $winner = 0;
  $shouldWeUpdateNextMatch = $setCountPlayer1 != 0 || $setCountPlayer2 != 0;
  if ($shouldWeUpdateNextMatch) {
    $winner = ($setCountPlayer1 > $setCountPlayer2) ? 1 : 2;
  }
  
  if (isset($_POST['playerKO'])) {
    $updateMatchSql .= 'playerKO = '. $_POST['playerKO'] . ', ';
    $winner = ($_POST['playerKO'] == 1 ? 2 : 1);
  } else {
    $updateMatchSql .= 'playerKO = 0, ';
  }
  
  $isFinalGame = $match['idTournamentRoundType'] == 1 && $match['matchOrder'] == 1;
  if (!$isFinalGame && $winner != 0) {
    $winnerRound = $match['idTournamentRoundType'] - 1;
    $winnerOrder = ceil($match['matchOrder'] / 2);
    $playerWinnerIndex = ($match['matchOrder'] % 2 == 0) ? 2 : 1;
    mysql_query('UPDATE tournamentMatch SET' .
        ' idPlayer' . $playerWinnerIndex . ' = ' . $_POST['player' . ($winner)] .
        ', idPlayer' . ($playerWinnerIndex + 2) . ' = ' . $_POST['player' . ($winner + 2)] .
        ' WHERE matchOrder = ' . $winnerOrder .
        ' AND idTournamentRoundType = ' . $winnerRound .
        ' AND idTournamentDraw = '. $match["idTournamentDraw"]);
  }
  
  $updateMatchSql .= 'winner = '. $winner . ', ';
  
  $insertScoreSql = '';
  $insertScoreSql .= 'INSERT INTO tournamentGameScore (idTournamentMatch, setIndex,
      idPlayer01, idPlayer02, score) VALUES ';
  for ($i = 0; $i < count($scoreToAdd); $i++) {
    $insertScoreSql .= '(' .$scoreToAdd[$i]['idTournamentMatch'] . ',' .$scoreToAdd[$i]['setIndex'] . 
        ',' .$scoreToAdd[$i]['idPlayer01'] . ',' .$scoreToAdd[$i]['idPlayer02'] .', '.$scoreToAdd[$i]['score'] .')';
    if ($i != count($scoreToAdd) - 1) {
      $insertScoreSql .= ',';
    }
  }
  mysql_query($insertScoreSql);
  
  $updateMatchSql .= ' matchOrder = matchOrder WHERE idTournamentMatch = '. $idMatch;
  //echo $updateMatchSql;
  mysql_query($updateMatchSql);
  
?>
<?php 
  global $tournamentId;
  $tournamentId = $match['idTournamentDraw'];
  include('../../page/getMatchJson.php');
?>
<script type="text/javascript">
  function scrollToMatch() {
    var matchOrder = <?php echo $match['matchOrder']; ?>;
    var idTournamentRoundType = <?php echo $match['idTournamentRoundType'];?>;
    $(window).scrollTop($('#' + idTournamentRoundType + '-' + matchOrder).offset().top)
  }
  setTimeout(scrollToMatch, 500);
</script>